package model

type InviteGem struct {
	Id     int
	OpenId string
	Invite string
	IsGet  string
}

type GeneralInvite struct {
	OpenId    string `json:"uniqueid"`
	ShareCode string `json:"share_code"`
	ShareId   int    `json:"sharePicId"`
}

type InviteGemServer interface {
	Create(invite *InviteGem) (err error)
	GetById(openId string) (invite InviteGem, err error)
	UpdateInvite(inviteInfo InviteGem) (err error)
	Update(inviteInfo InviteGem, key string, val interface{}) (err error)
}

type inviteGemServer struct {
}

func NewInviteGemServer() InviteGemServer {
	return &inviteGemServer{}
}

func (u *inviteGemServer) Create(invite *InviteGem) (err error) {
	sql := "INSERT INTO invite_gem (open_id, invite) VALUES (?, '')"
	stmt, err := Db.Prepare(sql)
	if err != nil {
		return
	}
	defer stmt.Close()

	res, err := stmt.Exec(invite.OpenId)
	if err != nil {
		return
	}
	id, err := res.LastInsertId()
	if err != nil {
		return
	}
	invite.Id = int(id)
	return nil
}

func (u *inviteGemServer) GetById(openId string) (invite InviteGem, err error) {
	err = Db.QueryRow("SELECT id, open_id, invite, is_get FROM invite_gem WHERE open_id = ? limit 1", openId).Scan(&invite.Id, &invite.OpenId, &invite.Invite, &invite.IsGet)
	return
}

func (u *inviteGemServer) UpdateInvite(inviteInfo InviteGem) (err error) {
	statement := "UPDATE invite_gem SET invite = ?, is_get = ? WHERE open_id = ?"
	stmt, err := Db.Prepare(statement)
	if err != nil {
		return
	}
	defer stmt.Close()

	_, err = stmt.Exec(inviteInfo.Invite, inviteInfo.IsGet, inviteInfo.OpenId)
	return
}

func (u *inviteGemServer) Update(inviteInfo InviteGem, key string, val interface{}) (err error) {
	statement := "UPDATE invite_money SET " + key + " = ? WHERE open_id = ?"
	stmt, err := Db.Prepare(statement)
	if err != nil {
		return
	}
	defer stmt.Close()

	_, err = stmt.Exec(val, inviteInfo.OpenId)
	return
}
